/**
 * 量表缓存管理器
 * 统一管理所有量表的缓存逻辑
 */
export class ScaleCacheManager {
  constructor(scaleType, userId) {
    this.scaleType = scaleType; // 'hamd', 'hama', 'ymrs'
    this.userId = userId;
    this.cacheKey = `scale_cache_${scaleType}_${userId}`;
    this.cacheDuration = 7 * 24 * 60 * 60 * 1000; // 7天过期
  }

  /**
   * 保存进度
   */
  save(data) {
    try {
      const cacheData = {
        ...data,
        timestamp: Date.now(),
        version: '1.0' // 版本号，用于未来升级兼容
      };
      
      uni.setStorageSync(this.cacheKey, JSON.stringify(cacheData));
      console.log(`[${this.scaleType}] 缓存已保存:`, cacheData);
      return true;
    } catch (error) {
      console.error(`[${this.scaleType}] 缓存保存失败:`, error);
      return false;
    }
  }

  /**
   * 读取缓存
   */
  load() {
    try {
      const cachedStr = uni.getStorageSync(this.cacheKey);
      
      if (!cachedStr) {
        console.log(`[${this.scaleType}] 无缓存数据`);
        return null;
      }

      const cacheData = JSON.parse(cachedStr);
      
      // 检查是否过期
      if (this.isExpired(cacheData.timestamp)) {
        console.log(`[${this.scaleType}] 缓存已过期`);
        this.clear();
        return null;
      }

      console.log(`[${this.scaleType}] 缓存已读取:`, cacheData);
      return cacheData;
    } catch (error) {
      console.error(`[${this.scaleType}] 缓存读取失败:`, error);
      this.clear();
      return null;
    }
  }

  /**
   * 清除缓存
   */
  clear() {
    try {
      uni.removeStorageSync(this.cacheKey);
      console.log(`[${this.scaleType}] 缓存已清除`);
      return true;
    } catch (error) {
      console.error(`[${this.scaleType}] 缓存清除失败:`, error);
      return false;
    }
  }

  /**
   * 检查是否过期
   */
  isExpired(timestamp) {
    return Date.now() - timestamp > this.cacheDuration;
  }

  /**
   * 异步加载并询问用户
   */
  async loadWithPrompt() {
    return new Promise((resolve) => {
      const cacheData = this.load();
      
      if (!cacheData) {
        resolve({ shouldRestore: false, data: null });
        return;
      }

      // 询问用户
      uni.showModal({
        title: '继续填写',
        content: '检测到您有未完成的量表，是否继续之前的进度？',
        confirmText: '继续填写',
        cancelText: '重新开始',
        success: (res) => {
          if (res.confirm) {
            resolve({ shouldRestore: true, data: cacheData });
          } else {
            this.clear();
            resolve({ shouldRestore: false, data: null });
          }
        },
        fail: () => {
          resolve({ shouldRestore: false, data: null });
        }
      });
    });
  }

  /**
   * 获取缓存统计信息
   */
  getInfo() {
    const cacheData = this.load();
    if (!cacheData) return null;

    return {
      scaleType: this.scaleType,
      savedAt: new Date(cacheData.timestamp).toLocaleString('zh-CN'),
      currentPage: cacheData.currentPage,
      answeredCount: cacheData.scores.filter(s => s !== null).length,
      totalCount: cacheData.scores.length,
      progress: `${Math.round(cacheData.scores.filter(s => s !== null).length / cacheData.scores.length * 100)}%`
    };
  }
}

/**
 * 清除所有量表缓存
 */
export function clearAllScaleCache(userId) {
  const scaleTypes = ['hamd', 'hama', 'ymrs'];
  let clearedCount = 0;

  scaleTypes.forEach(type => {
    const manager = new ScaleCacheManager(type, userId);
    if (manager.clear()) {
      clearedCount++;
    }
  });

  return clearedCount;
}

/**
 * 获取所有缓存信息
 */
export function getAllCacheInfo(userId) {
  const scaleTypes = ['hamd', 'hama', 'ymrs'];
  const scaleNames = {
    hamd: '汉密尔顿抑郁量表',
    hama: '汉密尔顿焦虑量表',
    ymrs: '杨氏躁狂评定量表'
  };
  const cacheInfoList = [];

  scaleTypes.forEach(type => {
    const manager = new ScaleCacheManager(type, userId);
    const info = manager.getInfo();
    if (info) {
      info.scaleName = scaleNames[type];
      cacheInfoList.push(info);
    }
  });

  return cacheInfoList;
}

